const SubModel = require('../models/sub-model')
const MediaService = require('../services/media-service')
const ArrayTool = require('../utils/array-tool')
const logger = require('../utils/console-logger')

const Jellyfin = require('../utils/media-server/jellyfin-server');

const syncFromMediaServerByTmdbids = async (tmdbids) => {
    if (!tmdbids || !tmdbids.length) return;
    const whereBuilder = countQuery => {
        countQuery.where('tmdbid', 'in', tmdbids)
    }
    const subList = await SubModel.list(SubModel.buildPaging({ pageSize: tmdbids.length }), whereBuilder)
    await syncFromMediaServer(subList)
}

const syncFromMediaServer = async (subs) => {
    if (!subs || !subs.length) return;
    for (let index = 0; index < subs.length; index++) {
        const sub = subs[index];
        try {
            if (sub.mediaType === 'movie') {
                const exists = await Jellyfin.getMovie(sub.title, sub.year.split('-')[0])

                logger.info('媒体库同步结果：', sub.title, exists ? true : false);
                if (exists) {
                    sub.status = 'playable'
                    await SubModel.updateBy({
                        status: sub.status,
                    }, { id: sub.id })
                }
            } else if (sub.mediaType === 'tv') {
                const seasons = JSON.parse(sub.seasons)
                for (let index = 0; index < seasons.length; index++) {
                    const season = seasons[index];
                    if ((season.lack && season.lack.length) || (season.find && season.find.length) || (season.download && season.download.length)) {
                        const existsEpisodes = await Jellyfin.getTvEpisodes(sub.title, undefined, season.season_number)
                        if (existsEpisodes && existsEpisodes.length) {  // 考虑媒体服务器错误
                            season.exists = existsEpisodes
                            if (season.find && season.find.length) {
                                season.find = ArrayTool.difference(season.find, existsEpisodes)
                            }
                            if (season.download && season.download.length) {
                                season.download = ArrayTool.difference(season.download, existsEpisodes)
                            }

                            if (season.lack && season.lack.length) {
                                season.lack = ArrayTool.difference(season.lack, existsEpisodes)
                            }
                        }
                    }
                }
                logger.info('媒体库同步结果：', sub.title, seasons);
                sub.seasons = JSON.stringify(seasons)
                await SubModel.updateBy({
                    seasons: sub.seasons,
                }, { id: sub.id })
            }
        } catch (e) {
            logger.error('媒体库同步失败', e.message)
        }
    }
}

const updateMediaInfo = async (subs) => {
    if (!subs || !subs.length) return;
    for (let index = 0; index < subs.length; index++) {
        const sub = subs[index];
        try {
            const media = await MediaService.getMedia(sub.tmdbid, sub.mediaType, false)
            if (media && media.info) {
                const info = JSON.parse(media.info)
                // 需要更新名称
                if (sub.title !== info.title) {
                    sub.title = info.title
                    await SubModel.updateBy({ title: sub.title }, { id: sub.id })
                    // TODO ?重命名媒体保存文件夹
                }
                // 更新季
                if (sub.mediaType === 'tv' && sub.seasons) {
                    const seasons = JSON.parse(sub.seasons)
                    let needUpdate = false
                    for (let j = 0; j < seasons.length; j++) {
                        const season = seasons[j];
                        const mediaSeason = await MediaService.getMediaSeason(sub.tmdbid, season.season_number, false)
                        if (mediaSeason) {
                            const seasonInfo = JSON.parse(mediaSeason.info)
                            const allEpisodes = seasonInfo.episodes.map(episode => episode.episode_number) // TMDB媒体信息新的所有的集
                            const insertedEpisodes = [] // 已入库的集
                            if (season.exists && season.exists.length) {
                                insertedEpisodes.push(...season.exists)
                            }
                            if (season.find && season.find.length) {
                                insertedEpisodes.push(...season.find)
                            }
                            if (season.download && season.download.length) {
                                insertedEpisodes.push(...season.download)
                            }
                            if (season.lack && season.lack.length) {
                                insertedEpisodes.push(...season.lack)
                            }
                            // 需要更新集
                            if (allEpisodes.length !== insertedEpisodes.length) {
                                const toInsertEpisodes = ArrayTool.difference(insertedEpisodes, allEpisodes)
                                season.episode_count = allEpisodes.length
                                season.lack = season.lack.push(...toInsertEpisodes)
                                needUpdate = true
                            }
                        }
                        
                    }

                    if (needUpdate) {
                        sub.seasons = JSON.stringify(seasons)
                        await SubModel.updateBy({ seasons: sub.seasons }, { id: sub.id })
                    }
                }

                logger.info(`[${sub.title}]TMDB媒体信息已更新`)
            }
        } catch (e) {
            logger.error(`[${sub.title}]TMDB媒体信息更新失败`, e.message)
        }
    }

}

module.exports = {
    syncFromMediaServer, syncFromMediaServerByTmdbids, updateMediaInfo
}